//
//  WeiboRefreshControl.swift
//  WEIBO_SWIFT
//
//  Created by 岳挺 on 15/7/5.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import FFAutoLayout

class WeiboRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        
        addSubview(refresh)
        
        refresh.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 200, height: 60))
        
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    //
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }
    
    var isloading = false
    var isFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame)
        
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing &&  !isloading {
            refresh.startLoadingAnimation()
            isloading = true
            return
        }
        
        if frame.origin.y < -50 && isFlag == false{
            print("箭头朝上")
            refresh.rotateArrowView(true)
//            refresh.coverView.hidden = true
            isFlag = true
        }else if frame.origin.y >= -50 && isFlag == true {
            print("箭头朝下")
//            refresh.coverView.hidden = false
            isFlag = false
            refresh.rotateArrowView(false)
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refresh.endLoadingAnimation()
        isloading = false
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var refresh : RefreshView = RefreshView.refreshView()
}

class RefreshView : UIView {
    
    @IBOutlet weak var loadingView: UIImageView!
    @IBOutlet weak var arrowView: UIImageView!
    @IBOutlet weak var coverView: UIView!
    class func refreshView() ->RefreshView{
         return NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView
    }
    
    func rotateArrowView (clockWise : Bool){
        var angle = M_PI
        angle += clockWise ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.arrowView.transform = CGAffineTransformRotate(self.arrowView.transform, CGFloat(angle))
        }
    }
    
    //开启加载动画
    func startLoadingAnimation (){
        coverView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1
        
        loadingView.layer.addAnimation(anim, forKey: nil)
    }
    
    //关闭动画
    func endLoadingAnimation (){
        coverView.hidden = false
        loadingView.layer.removeAllAnimations()
    }
}
